<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/1/8
 * Time: 13:37
 */

namespace Modules\Shop\Service;

use HiCommon\Helper;
use HiCommon\Repository\InvoiceApplyRepository;
use HiCommon\Repository\InvoiceApplyExtendRepository;

use HiCommon\Repository\RoadRescueOrderRepository;
use HiCommon\Repository\StoreOrderRepository;
use HiCommon\Repository\OrderRepairstoreRepository;
use HiCommon\Repository\OrderCheckpointRepository;

class InvoiceService
{

    /**
     *	获取所有的发票申请列表
     *	hinq 2019 11 19
     *
     **/
    public function get_list( array $arr_search ){
        try{
            $arr_option['where'] = ['status'=>1 , 'repairstore_id' => shop_shop_id() ];
            $arr_option['with'] = ['user','address','extend'];
            $arr_list = InvoiceApplyRepository::get_list( (array) $arr_option , (array) $arr_search );
            $arr_list->appends($arr_search);//添加链接参数
            $arr_list = list_page_data( $arr_list , $arr_search );
            //统计已开票和未开票的数量
            foreach ( $arr_list['data'] as $key => &$value ){
                $kai = 0;
                $all = 0;
                foreach ( $value['extend'] as $k => $val ){
                    $all++;
                    if( $val['status'] == 2 ){
                        $kai++;
                    }
                }
                $value['kai'] = $kai;
                $value['all'] = $all;
                unset( $value['extend'] );
            }
            return hello_success('成功',$arr_list);
        }catch( \Exception $exception ){
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
    }

    /**
     *	获取指定的发票的详细信息
     *	hinq 2019 11 20
     *
     **/
    public function detail( array $arr_search ){
        try{
            //获取指定的申请信息
            // $arr_option['with'] = ['user','address','extend','extend.order','extend.order.getOrderGoods'];
            $arr_option['with'] = ['user','address','extend','address'];
            $arr_list = InvoiceApplyRepository::get_one_where( (array) ['id'=>$arr_search['id'] ] , (array) $arr_option )->toarray();
            return $arr_list;
        }catch( \Exception $exception ){
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
    }


    /**
     *	获取指定的发票关联的订单信息
     *	hinq 2019 11 20
     *
     **/
    public function goods_order( array $arr_input ){
        try{
            $nId = $arr_input['id'];
            $arr_option['where'] = ['link_id'=>$nId];
            //关联的订单类别
            $arr_option['field'] = ['id','link_id','goods_order_id','type','status','remark'];
            $arr_option['with'] = ['order'=>function( $query ){
                $query->select('id','order_no','shop_id','pay_amount','created_at');
            },'order.shop'=>function( $query ){
                $query->select('id','name');
            },'order_repairstore'=>function( $query ){
                $query->select('id','order_number','pay_price','created_at','shop_id');
            },'order_repairstore.shop','order_checkpoint'=>function( $query ){
                $query->select('id','order_sn','shop_id','price','created_at');
            },'order_checkpoint.shop'=>function( $query ){
                $query->select('id','name');
            },'order_roadrescus'=>function( $query ){
                $query->select('id','order_sn','shop_id','price','created_at');
            },'order_roadrescus.to_shop'=>function( $query ){
                $query->select('id','name');
            }];
            $arr_list = InvoiceApplyExtendRepository::get_list( (array) $arr_option )->toArray();
            $data = [];
            foreach ($arr_list['data'] as $key => $value) {
                $str = '';
                if( $value['type'] == 1 ){
                    $str = 'order';
                    $data[$key]['order_sn'] = $value['order']['order_no'];
                    $data[$key]['pay_price'] = $value['order']['pay_amount'];
                    $data[$key]['created_at'] = $value['order']['created_at'];
                    $data[$key]['shop_name'] = $value['order']['shop']['name'];
                }else if( $value['type'] == 2 ){
                    $data[$key]['order_sn'] = $value['order_repairstore']['order_number'];
                    $data[$key]['pay_price'] = $value['order_repairstore']['pay_price'];
                    $data[$key]['created_at'] = $value['order_repairstore']['created_at'];
                    $data[$key]['shop_name'] = $value['order_repairstore']['shop']['name'];
                }else if( $value['type'] == 3 ){
                    $data[$key]['order_sn'] = $value['order_checkpoint']['order_sn'];
                    $data[$key]['pay_price'] = $value['order_checkpoint']['price'];
                    $data[$key]['created_at'] = $value['order_checkpoint']['created_at'];
                    $data[$key]['shop_name'] = $value['order_checkpoint']['shop']['name'];
                }else if( $value['type'] == 4 ){
                    $data[$key]['order_sn'] = $value['order_roadrescus']['order_sn'];
                    $data[$key]['pay_price'] = $value['order_roadrescus']['price'];
                    $data[$key]['created_at'] = $value['order_roadrescus']['created_at'];
                    $data[$key]['shop_name'] = $value['order_roadrescus']['to_shop']['name'];
                }
                $data[$key]['is_invoice'] = $value['status'] == 2 ? '已开发票' : '未开发票';
                $data[$key]['is_invoice_status'] = $value['status'];
                $data[$key]['remark'] = $value['remark'];
                $data[$key]['id'] = $value['id'];
                $data[$key]['status'] = $value['status'];
                $data[$key]['order_id'] = $value['goods_order_id'];
                $data[$key]['type'] = $value['type'];
                $data[$key]['link_id'] = $value['link_id'];
            }
            $temp = [
                "code"=> 0,
                "msg"=> "",
                "count"=> $arr_list['total'],
                "data"=>$data
            ];
            return $temp;
        }catch( \Exception $exception ){
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
    }

    /**
     *	确认发送发票信息
     *	hinq 2019 11 20
     *
     **/
    public function check_order( array $arr_search ){
        try{
            //验证当前商品是否已经开过发票
            if( empty( $arr_search['shenqin_status'] ) ){
                return hello_error('请选择操作类型');
            }
            if( $arr_search['shenqin_status'] == 2 ){   //成功开票的时候才填写张数
                if( empty( $arr_search['num'] ) ){
                    return hello_error('请输入开发票的张数');
                }
            }
            if( empty( $arr_search['content'] ) ){
                return hello_error('请输入开票的备注信息');
            }
            if( empty( $arr_search['id'] ) ){
                return hello_error('参数错误');
            }
            //根据申请的发票id获取订单数
            $arr_option['where'] = ['link_id' => $arr_search['id']];
            $extend = InvoiceApplyExtendRepository::get_all( $arr_option )->toarray();
            $goods_ids = [];  //所有的订单id集合
            $type = '';
            foreach ( $extend as $key => $vo ){
                $goods_ids[] = $vo['goods_order_id'];   //所有的商品id集合
                $type = $vo['type'];  //订单类型
            }
            \DB::beginTransaction();
            $data['id'] = (int)$arr_search['id'];
            $data['shenqin_status'] = (int)$arr_search['shenqin_status'];
            $is_invoice = 0; // 默认未开票
            if( $arr_search['shenqin_status'] == 2 ){   //开票成功
                $data['number'] = (int)$arr_search['num'];
                $is_invoice = 1;
            }
            $data['content'] = $arr_search['content'];
            $res = InvoiceApplyRepository::edit_one( (array) $data);  //修改订单信息

            $temp['is_invoice'] = $is_invoice;  //开票成功将订单设置为已开票  开票失败将订单设置为未开票（可以重新开票）
            $res2 = true;
            if( $type == 1 ){           //普通订单
                //修改订单信息已开发票
                $res2 = StoreOrderRepository::edit_one_whereIn( (array) ['key'=>'id' , 'value'=> $goods_ids ], (array) $temp );
            }else if( $type == 2 ){     //服务订单
                //修改订单信息已开发票
                $res2 = OrderRepairstoreRepository::edit_one_whereIn( (array) ['key'=>'id' , 'value'=> $goods_ids ] , (array) $temp );
            }else if( $type == 3 ){     //预约订单
                //修改订单信息已开发票
                $res2 = OrderCheckpointRepository::edit_one_whereIn( (array) ['key'=>'id' , 'value'=> $goods_ids ] , (array) $temp );
            }else if( $type == 4 ){     //道路救援
                //修改订单信息已开发票
                $res2 = RoadRescueOrderRepository::edit_one_whereIn( (array) ['key'=>'id' , 'value'=> $goods_ids ] , (array) $temp );
            }
            $arr_where['link_id'] = (int) $arr_search['id'];
            $arr_data['status'] = 2;
            $arr_data['remark'] = $arr_search['content'];
            $res3 = InvoiceApplyExtendRepository::edit_where( (array) $arr_where , (array) $arr_data );  //修改订单信息
            if( $res && $res2 && $res3 ){
                \DB::commit();
                return hello_success('ok');
            }else{
                \DB::rollback();  //回滚
                return hello_error('开票失败');
            }
        }catch(\Exception $exception ){
            \DB::rollBack();
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
    }


}